package com.yan.superfw_weixin_push.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yan.superfw_weixin_push.entity.Weather;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class WeatherUtil {


    public static String district_id;
    public static String ak;

    @Value("${yan.district_id}")
    public void setDistrict_id(String district_id) {
        WeatherUtil.district_id = district_id;
    }

    @Value("${yan.ak}")
    public void setAk(String ak) {
        WeatherUtil.ak = ak;
    }





    public static Weather getWeather(){
        RestTemplate restTemplate = new RestTemplate();
        Map<String,String> map = new HashMap<>();
        map.put("district_id",district_id);
        map.put("data_type","all");
        map.put("ak",ak);
        String res = restTemplate.getForObject(
                "https://api.map.baidu.com/weather/v1/?district_id={district_id}&data_type={data_type}&ak={ak}",
                String.class,
                map);
        JSONObject json = JSONObject.parseObject(res);
        JSON location=json.getJSONObject("result").getJSONObject("location");
        JSONArray forecasts = json.getJSONObject("result").getJSONArray("forecasts");
        List<Weather> weathers = forecasts.toJavaList(Weather.class);
        JSONObject now = json.getJSONObject("result").getJSONObject("now");
        Weather weather = weathers.get(0);
        weather.setText_now(now.getString("text"));
        weather.setTemp(now.getString("temp"));
        HashMap hashMap=JSON.parseObject(location.toString(),HashMap.class);

        Object city=hashMap.get("city");
        weather.setCity((String) city);
        return weather;
    }

}
